package com.mall.controller;


import com.mall.entity.Orderproduct;
import com.mall.entity.Orders;
import com.mall.entity.Product;
import com.mall.httpResult.HttpResult;
import com.mall.httpResult.ResultCodeEnum;
import com.mall.service.OrderproductService;
import com.mall.service.OrdersService;
import com.mall.service.ProductService;
import com.mall.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fire
 * @since 2020-04-16
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private OrdersService orderService;

    @Autowired
    private HashOperations hashOperations;
    
    @Autowired
    private OrderproductService orderproductService;

    @Autowired
    private ProductService productService;
    
    @GetMapping("listOrders/{userId}")
    @ApiOperation("查看用户订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "订单状态：全部-1、待发货0、待收货1、已收货2、退货3", required = false, dataType = "int"),
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true , dataType = "int"),
            @ApiImplicitParam(name = "pageNo", value = "当前页", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示数量", dataType = "int")
    })
    public HttpResult getProductByStatus(@PathVariable(value = "userId") int userId ,
                                         @RequestParam(value = "status", required = false, defaultValue = "-1") String status ,
                                         @RequestParam(value = "pageNo", required = false, defaultValue = "0") int pageNo,
                                         @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize){

        try{
            return HttpResult.success(userService.listOrdersByUserIdAndStatus(userId,status,pageNo,pageSize));
        }catch (Exception e){
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR,e.getMessage());
        }
    }

    @GetMapping("stars/{userId}")
    @ApiOperation("查看用户评价,返回的是orderproduct集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true , dataType = "int"),
            @ApiImplicitParam(name = "status", value = "订单状态", required = true , dataType = "String")
    })
    public HttpResult getuserStars(@PathVariable(value = "userId") int userId ,
                                   @RequestParam(value = "status", required = false, defaultValue = "-1") String status
    ){

        try{
            return HttpResult.success(userService.listOrderProductByUserId(userId , status));
        }catch (Exception e){
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR,e.getMessage());
        }
    }

    @PutMapping("evaluate")
    @ApiOperation("用户评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderproduct", value = "Orderproduct", required = true , dataType = "Orderproduct")
    })
    public HttpResult getuserStars(@RequestBody Orderproduct orderproduct ){

        try{
            return HttpResult.success(userService.evaluate(orderproduct));
        }catch (Exception e){
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR,e.getMessage());
        }
    }

    @PutMapping("cancleOrder/{userId}/{orderId}")
    @ApiOperation("用户申请退款")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId" , value = "用户Id", required = true , dataType = "int"),
            @ApiImplicitParam(name = "orderId" , value = "订单Id", required = true , dataType = "int"),
            @ApiImplicitParam(name = "description" , value = "申请退货原因", required = true , dataType = "String")
    })
    public HttpResult cancleOrder(@PathVariable(value = "userId") int userId , @PathVariable(value = "orderId") int orderId,
                                  @RequestParam(value = "description" , required = true) String description

    ){
        try {
            if (userService.returnOrder(userId,orderId,description)){
                return HttpResult.success();
            }
            return HttpResult.failure(ResultCodeEnum.ORDER_NOTFOUND);
        }catch (Exception e){
            return HttpResult.failure(ResultCodeEnum.ORDER_NOTFOUND);
        }
    }
    @PutMapping("orderReturnStatus/{userId}/{orderId}")
    @ApiOperation("用户查看退款进度")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId" , value = "用户Id", required = true , dataType = "int"),
            @ApiImplicitParam(name = "orderId" , value = "订单Id", required = true , dataType = "int")
    })
    public HttpResult getOrderReturnStatus(@PathVariable(value = "userId") int userId , @PathVariable(value = "orderId") int orderId){
        try {
            return userService.getOrderReturnStatus(userId,orderId);
        }catch (Exception e){
            return HttpResult.failure(ResultCodeEnum.ORDER_NOTFOUND);
        }
    }

    @PostMapping("/pay/{userId}")
    @ApiOperation("用户结算购物车")
    public HttpResult pay(@PathVariable int userId, @RequestBody List<Product> products, @RequestParam String address) {

        // 生成订单
        BigDecimal price = BigDecimal.valueOf(0);
        for (Product product : products) {
            price = product.getLaunchPrice().multiply(BigDecimal.valueOf(product.getCount().longValue()));
        }
        int orderId = orderService.addOrder(userId, address, price);
        // 生成订单详细
        orderproductService.addOrderproduct(orderId, products);
        
        // 删除购物车
        for (Product product : products) {
            Product p = productService.selectById(product.getId());
            productService.updateById(product.setCount(p.getCount() - product.getCount()));
            hashOperations.delete("shoppingCar:" + userId + "", product.getId() + "");
        }
        
        return HttpResult.success();
    }
}

